package sair.player.ui;

import java.util.List;

import sair.player.PlayerActivity;
import sair.player.acts.PlayerActions;
import sair.sacoms.LRC;
import sair.sacoms.until.LrcLine;

public class FlushLRCThread implements Runnable {
	private PlayerActivity pa;
	private LRC lrc;
	private boolean isContinue = true;
	private static final int whileTime = 200;

	public FlushLRCThread(LRC lrc, PlayerActivity pa) {
		this.lrc = lrc;
		this.pa = pa;
	}

	@Override
	public void run() {
		if (pa == null || lrc == null)
			return;
		List<LrcLine> list = lrc.getLrcLines();
		String[] listData = getListData(list);
		int[] timeData = getListTime(list);
		pa.getLrcListC().setListData(listData);
		PlayerActions pacti = pa.getPA();
		int mp3MaxTime = pacti.getMp3MaxTime();
		while (isContinue) {
			int nowTime = (int) (((float) mp3MaxTime) * pacti.getNowPos());
			int i = getApproximate(nowTime, timeData);
			pa.getPA().flushLRCUI(i, list.size());
			try {
				Thread.sleep(whileTime);
			} catch (InterruptedException e) {

			}
		}
	}

	private static int[] getListTime(List<LrcLine> list) {
		int[] datas = new int[list.size()];
		for (int i = 0; i < datas.length; i++)
			datas[i] = (int) (list.get(i).getTime() / 1000);
		return datas;
	}

	private static String[] getListData(List<LrcLine> list) {
		String[] datas = new String[list.size()];
		for (int i = 0; i < datas.length; i++)
			datas[i] = list.get(i).getLyric();
		return datas;
	}

	public void Stop() {
		isContinue = false;
		pa.ui.getLRCLabel().setText(pa.ui.lrcShowInfo);
		if (this.pa != null) {
			pa.getLrcListC().setListData(new String[] {});
			pa.getPA().flushLRCUI(0, 1);
		}
	}

	private static int getApproximate(int x, int[] src) {
		int index = src.length - 1;
		for (; index > 0; index--) {
			if (src[index] < x)
				return index;
		}
		return 0;
	}

}
